<template>
  <view class="order-row">
    <!-- 顶部 Tabs 切换 -->
    <u-tabs keyName="title" :list="tabsList" @change="onChangeTabs" lineHeight="5rpx" lineWidth="100rpx"></u-tabs>
    <view class="inner-style pdt-2">
      <!-- 订单列表展示 -->
      <!-- <view class="loading" v-if="loading">
        <u-loading-icon mode="flower"></u-loading-icon>
      </view> -->
      <scroll-view class="order-list" scroll-y @scrolltolower="loadMore">
        <view v-for="(order, index) in orders" :key="index" class="pd-2 bgf border-radius mgb-2">
          <view class="dis-f justify-between">
            <!-- 订单标题 -->
            <view v-if="order.orderType == 7 && order.toBeUsedOrPayPo.ebMerActivity.name"
              class="base-ellipsis font-s16">
              {{ order.toBeUsedOrPayPo.ebMerActivity.name }}
            </view>
            <view v-else-if="order.orderType == 7" class="base-ellipsis font-s16">
              活动已删除请联系商家处理
            </view>
            <view class="color06 wsn">
              <template v-if="order.refundStatus">
                <view v-if="order.refundStatus === 1" style="color: green;">申请中,待商家确认</view>
                <view v-else-if="order.refundStatus === 2" style="color: red;">已退款</view>
                <view v-else-if="order.refundStatus === 3" style="color: orange;">商家已确认,退款中</view>
              </template>
              <template v-else>
                <view style="color: red;" v-if="order.status === 1 ">待洗衣</view>
                <view v-if="order.status === 2">待评价</view>
                <view style="color: blue;" v-if="order.status === 6">洗衣中</view>
                <view v-if="order.status === 4">超时未使用,已退款</view>
                <view style="color: #199f33;" v-if="order.status === 3">已完成</view>
                <view v-if="order.status == 5">已取消</view>
              </template>
            </view>
          </view>
          <view class="cf mgt-2">
            <image v-if="order.orderType == 7" class="icon-img2 fl border-radius" :src="order.toBeUsedOrPayPo.ebMerActivityTicket.icon.includes('http') ?
              order.toBeUsedOrPayPo.ebMerActivityTicket.icon : getImg + order.toBeUsedOrPayPo.ebMerActivityTicket.icon"
              mode="">
            </image>

            <view class="mgl-2 fl" style="width: calc(100% - 150rpx)">
              <view style="font-weight: bold" class="font-semlbold base-ellipsis" v-if="order.orderType == 7">
                {{ order.toBeUsedOrPayPo.ebMerActivityTicket.name }}
              </view>

              <view class="color06 base-ellipsis" v-if="order.orderType == 7">
                {{ order.toBeUsedOrPayPo.ebMerActivity.merName ? order.toBeUsedOrPayPo.ebMerActivity.merName : '' }}
              </view>
              <view class="">
                <!-- <span class="mgr-4">数量 {{ order.totalNum }}</span> -->
                <span v-if="order.toBeUsedOrPayPo.storeOrder.paid" style="color: red;">实付 ￥{{ order.payPrice ?
                  Number(order.payPrice).toFixed(2) : '' }}</span>
                <span v-else-if="!order.toBeUsedOrPayPo.storeOrder.paid" style="color: red;">待付款 ￥{{
                  Number(order.toBeUsedOrPayPo.storeOrder.payPrice).toFixed(2) }}</span>
              </view>
              <view class="" v-if="order.toBeUsedOrPayPo.storeOrder.paid">
                <span class="mgr-4">支付时间</span>
                <span> {{ order.createTime }}</span>
              </view>
              <view class="" v-else-if="!order.toBeUsedOrPayPo.storeOrder.paid">
                <span class="mgr-4">订单创建时间</span>
                <span> {{ order.toBeUsedOrPayPo.storeOrder.createTime }}</span>
              </view>
            </view>
            <view class="cf" style="display: flex; justify-content: flex-end">
              <view class="fr mgt-2" style="display: flex; gap: 20rpx; font-size: 22rpx">
                <button class="btn" style="border: 1rpx solid orange; color: orange"
                  v-if="order.status === 0 && order.orderType != 5" type="default" shape="circle"
                  @click="payOrder(order)">
                  付款
                </button>

                <button class="btn" v-if="order.status === 2" shape="circle" @click="reviewOrder(order)"
                  style="border: 1rpx solid orange; color: orange">评价</button>

              </view>
            </view>
          </view>
        </view>
        <view v-if="hasMore" class="load-more">
          <u-loading-icon mode="circle"></u-loading-icon>
        </view>
        <view v-else class="no-more">没有更多订单了</view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { orderList, delOrder } from "../../../utils/api/local.js";
import { IMG_URL } from "../../../config/index.js";

export default {
  data() {
    return {
      active: "0", // 当前活动的 Tab
      orders: [],
      getImg: IMG_URL,
      tabsList: [
        { refundStatus: "", name: "0", status: "", title: "全部", orderTypeStr: '7' },
        { refundStatus: 0, name: "1", status: "0", title: "待付款", orderTypeStr: '7' },
        { refundStatus: 0, name: "2", status: "1", title: "待取货", orderTypeStr: '7' },
        { refundStatus: 0, name: "3", status: "6", title: "洗衣中", orderTypeStr: '7' },
        { refundStatus: 0, name: "4", status: "2", title: "待评价", orderTypeStr: '7' },
        { refundStatus: 0, name: "5", status: "3", title: "已完成", orderTypeStr: '7' },
      ],
      params: {
        page: 1, // 当前页码
        limit: 10, // 每页数据量
      },
      hasMore: true, // 是否有更多数据
      remainingTimes: {}, // 存储每个订单的剩余时间
      timer: null, // 定时器 ID
      loading: true // 首次加载动画
    };
  },
  onPullDownRefresh() {
    console.log('下拉刷新')
    setTimeout(() => {
      console.log('下拉刷新停止')
      uni.stopPullDownRefresh()
    }, 5500)
  },
  // 上拉加载
  onReachBottom() {
    console.log('上拉加载')
    this.params.page++
    this.getData()
    setTimeout(() => {
      console.log('上拉加载停止')

      uni.stopPullDownRefresh()
    }, 5500)
  },
  onLoad(option) {
    this.active = option.status || "0";
    this.getData()
    // this.fetchOrderList().then(() => {
    //   this.loading = false;
    // });
  },
  methods: {
    onChangeTabs(active) {
      this.active = active;
      this.params.page = 1;
      this.orders = [];
      this.remainingTimes = {};
      this.hasMore = true;
      this.loading = true;
      this.fetchOrderList().then(() => {
        this.loading = false;
      });
    },
    getData() {
      const currentTab = this.tabsList.find((tab) => {
        return tab.title === this.active.title;
      });
      const refundStatus = currentTab ? currentTab.refundStatus : "";
      var params = {
        status: currentTab ? currentTab.status : "",
        userId: uni.getStorageSync('uid'),
        page: this.params.page,
        limit: this.params.limit,
        refundStatus: refundStatus,
        orderTypeStr: currentTab ? currentTab.orderTypeStr : '7'
      }
      orderList(params).then(res => {
        this.orders = this.orders.concat(res.data.list)
        this.hasMore = this.params.page * this.params.limit <= res.data.total;
        this.orders.forEach((order) => {
          order.id = order.id || order.toBeUsedOrPayPo.storeOrder.id;
          this.updateRemainingTime(order);
        });
      })
    },
    async fetchOrderList() {
      try {
        const currentTab = this.tabsList.find((tab) => {
          return tab.title === this.active.title;
        });
        const refundStatus = currentTab ? currentTab.refundStatus : "";
        const res = await orderList({
          status: currentTab ? currentTab.status : "",
          userId: uni.getStorageSync('uid'),
          page: this.params.page,
          limit: this.params.limit,
          refundStatus: refundStatus,
          orderTypeStr: currentTab ? currentTab.orderTypeStr : '7'
        });
        if (res && res.code === 200 && res.data) {
          const filteredList = res.data.list.filter((order) => !(order.orderType === 5 && order.status === 0));

          this.orders = this.params.page === 1 ? filteredList : [...this.orders, ...filteredList];
          this.hasMore = this.params.page * this.params.limit <= res.data.total;


          this.orders.forEach((order) => {
            order.id = order.id || order.toBeUsedOrPayPo.storeOrder.id;
            this.updateRemainingTime(order);
          });
        }
      } catch (err) {
        console.error("加载订单失败", err);
        this.loading = false;
      }
    },
    deleteOrder(order) {
      uni.showModal({
        title: "删除订单", // 标题
        content: "此操作将会彻底删除订单，请确定是否执行此操作？", // 内容
        success: (modelRes) => {
          if (modelRes.confirm) {
            const data = {
              orderId: order.orderId,
              userId: uni.getStorageSync('uid'),
              id: order.id,
            };
            delOrder(data)
              .then((res) => {
                if (res) {
                  uni.showToast({
                    title: "删除成功",
                    icon: "success",
                  });
                  this.fetchOrderList();
                }
              })
              .catch((err) => {
                console.error("删除订单失败", err);
              });
          } else if (modelRes.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },
    payOrder(order) {
      let status = this.getStatus(order);
      uni.navigateTo({
        url: "/pages_h5/local_life/components/order_detail?orderId=" + order.orderId + "&status=" + status + "&id=" + order.id,
      });
    },
    onRefund(order) {
      var d = new Date(order.createTime.toString().replace(/-/g, "/"));
      var todaysDate = new Date();
      if (d.setHours(0, 0, 0, 0) == todaysDate.setHours(0, 0, 0, 0)) {
        uni.navigateTo({
          url: "/pages_h5/local_life/components/kjzfTuikuan?order=" + JSON.stringify(order)
        });
        return
      } else {
        uni.showToast({
          title: "订单过期，无法申请退款，请联系商家处理",
          icon: "none",
          duration: 2000
        });
        return;
      }
    },
    viewCoupon(order) {
      let status = this.getStatus(order);
      uni.navigateTo({
        url: "/pages_h5/local_life/components/order_detail?orderId=" + order.orderId + "&status=" + status + "&id=" + order.id,
      });
    },
    reviewOrder(order) {
      uni.navigateTo({
        url: "/pages_h5/local_life/components/evaluat?orderId=" + order.orderId + "&id=" + order.id,
      });
    },
    reorder(order) {
      // if (isExpired(order.toBeUsedOrPayPo.ebMerActivity.endTime)) {
      //   this.$toast("该活动已过期");
      // } else {
      //   uni.navigateTo({
      //     url: "/pages/index_tabs/local_life/active_detail?id=" + order.ebMerActivityId + "&businessId=" + order.ebMerId,
      //   });
      // }
    },
    getStatus(order) {
      let status = order.status;
      if (order.refundStatus === 1) {
        status = 4;
      } else if (order.refundStatus === 2) {
        status = 3;
      } else if (order.status === 4) {
        status = 7;
      }
      return status;
    },
    refundProgress(order) {
      let status = this.getStatus(order);
      uni.navigateTo({
        url: "/pages_h5/local_life/components/refund?orderId=" + order.orderId + "&status=" + status + "&id=" + order.id,
      });
    },
    loadMore() {
      if (this.hasMore) {
        this.params.page++;
        this.fetchOrderList();
      }
    },
    updateRemainingTime(order) {
      if (!order.createTime || !order.payEndTime) {
        this.$set(this.remainingTimes, order.id, "时间信息不完整");
        return;
      }

      const createDate = new Date(order.createTime.replace(" ", "T")).getTime();
      const endDate = new Date(order.payEndTime.replace(" ", "T")).getTime();
      const now = Date.now();
      const remainingTime = endDate - now;

      if (remainingTime <= 0) {
        this.$set(this.remainingTimes, order.id, "已过期");
      } else {
        const hours = Math.floor((remainingTime / (1000 * 60 * 60)) % 24);
        const minutes = Math.floor((remainingTime / (1000 * 60)) % 60);
        const seconds = Math.floor((remainingTime / 1000) % 60);
        this.$set(this.remainingTimes, order.id, `${hours}:${minutes}:${seconds}`);
      }
    },
    startTimer() {
      this.timer = setInterval(() => {
        this.orders.forEach((order) => {
          this.updateRemainingTime(order);
        });
      }, 1000);
    },
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
  },
  onShow() {
    // this.fetchOrderList();
    this.startTimer();
  },
  beforeDestroy() {
    this.clearTimer();
  },
};
</script>

<style lang="less" scoped>
.order-row {
  height: 100vh;
  padding:0 20rpx;
  overflow-y: hidden;
  background-color: #f8f8f8;
}

.inner-style {
  padding: 20rpx;
  border-radius: 20rpx;
  font-size: 28rpx;
}

.loading {
  display: flex;
  justify-content: center;
  padding: 20rpx;
}

.order-list {
  height: 90vh;
  padding-bottom: 20rpx;
}

.dis-f {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.font-s16 {
  font-size: 32rpx;
}

.base-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.color06 {
  color: #999999;
  margin: 10rpx 0;
}

.wsn {
  width: auto;
}

.pdt-2 {
  padding-top: 20rpx;
}

.pd-2 {
  padding: 20rpx;
}

.bgf {
  background-color: #ffffff;
}

.border-radius {
  border-radius: 10rpx;
}

.mgb-2 {
  margin-bottom: 20rpx;
}

.cf {
  clear: both;
}

.mgt-2 {
  margin-top: 20rpx;
}

.fl {
  float: left;
}

.mgl-2 {
  margin-left: 20rpx;
}

.fr {
  float: right;
}

.mgr-4 {
  margin-right: 40rpx;
}

.load-more {
  text-align: center;
  color: #999999;
  padding: 10px 0;
}

.no-more {
  text-align: center;
  color: #999999;
  padding: 10px 0;
}

.icon-img2 {
  width: 100rpx;
  height: 100rpx;
}

.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: black;
  border-radius: 20rpx;
  background-color: none;
}
</style>
